<?php

namespace app\applet\controller;

use app\share\model\Token;
use Qiniu\Auth;
use Qiniu\Sms\Sms;
use think\Db;
use think\Session;
use think\Validate;
use think\Loader;
class Msg
{
    private $template_id="1277055136643956736";
    public function __construct()
    {
        Loader::import('Qiniu.autoload');
        $accessKey=config("qiniu.access_key");
        $secretKey=config("qiniu.secret_key");
        $this->send=new Sms(new Auth($accessKey, $secretKey));
    }

    /**
     *短信验证码
     *
     */
    public function phoneCode()
    {
        $input = input();
        $validate = new Validate([
            ['mobile', 'require', '手机号码不能为空']
        ]);
        if(!$validate->check($input))
        {
            returnJson(-2003,$validate->getError());
        }
        $mobile[]=$input['mobile'];
        $code = rand(1000, 9999);
        $parameters=['code'=>$code];
        $obj = $this->send->sendMessage( $this->template_id,$mobile,$parameters);
//        $obj[0]['job_id'] = 1;
        if(!empty($obj[0]['job_id']))
        {
            $insert['phone']       = $input['mobile'];
            $insert['code']        = $code;
            $insert['create_time'] = time();
            Db::name("code_msg")->insert($insert);
            returnJson(200,"短信发送成功");
        }else{
            returnJson(-2003,"发送失败");
        }
    }

    /**
     * 发送短信
     */
    public function sendMsg(){
        $input=input();
        $validate = new Validate([
            ['mobile', 'require', '手机号码不能为空'],
        ]);
        if(!$validate->check($input))
        {
          returnJson(-2003,$validate->getError());
        }
        $member_id= get_header_id("token");
        if($member_id>0){

            $phone = $input['mobile'];
            #查询验证码是否存在5分钟有效
            $msg_code = Db::name("code_msg")
                ->field("id,code,create_time")
                ->where(['phone'=>$phone,'status'=>0])
                ->order(['id'=>'desc'])
                ->find();

            if($msg_code['create_time'] + 5 * 60 > time())
            {
                returnJson(-2004,"五分钟以后不能再次发送");
            }

        }
        Session::start();
        $mobile=$input['mobile'];
        $template_id="1277055136643956736";
        $mobiles[]=$mobile;
        Loader::import('Qiniu.autoload');
        $accessKey=config("qiniu.access_key");
        $secretKey=config("qiniu.secret_key");
        $auth=new \Qiniu\Auth($accessKey, $secretKey);
        $msg=new \Qiniu\Sms\Sms($auth);
        $shu = rand(1000, 9999);
        $parameters=['code'=>$shu];
        $rst=$msg->sendMessage( $template_id,$mobiles,$parameters);
        if(!empty($rst[0]['job_id'])){
            $insert['phone']       = $input['mobile'];
            $insert['code']        = $shu;
            $insert['create_time'] = time();
            Db::name("code_msg")->insert($insert);
            returnJson(200,"短信发送成功");
        }
        returnJson(-2003,"发送失败");
    }





}